package cn.yilongquan.service.impl;

import cn.yilongquan.mapper.ParamMapper;
import cn.yilongquan.service.ParamService;
import cn.yilongquan.system.domain.Param;
import cn.yilongquan.system.query.ParamQuery;
import cn.yilongquan.user.domain.BlogArticle;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.data.mongodb.core.query.Query;
import java.util.Date;
import java.util.List;

import cn.yilongquan.util.MinioUtil; // 工具类封装 MinIO 操作
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.web.multipart.MultipartFile;

@Service
public class ParamServiceImpl implements ParamService {
    @Resource
    private ParamMapper paramMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    // 注入 MinIO 工具类（封装上传逻辑，也可直接注入 MinioClient）
    @Autowired
    private MinioUtil minioUtil;

    @Override
    public List<Param> findPage(ParamQuery query) {
        // 计算分页起始位置
        query.setPage((query.getPage() - 1) * query.getSize());
        return paramMapper.findPage(query);
    }

    @Override
    public void add(Param param) {
        param.setCreateTime(new Date());
        param.setUpdateTime(new Date());
        paramMapper.insert(param);

        //同步到mongodb里面
        BlogArticle blogParam = new BlogArticle();
        //类的复制，字段和类型必须一致
        BeanUtils.copyProperties(param, blogParam);

        mongoTemplate.save(blogParam);

    }


    // 原有更新方法（扩展：同步图片 URL 到 MongoDB）
    @Override
    public void update(Param param) {
        param.setUpdateTime(new Date());
        paramMapper.update(param);
    }

    @Override
    public void delete(Long id) {
        paramMapper.delete(id);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        paramMapper.deleteBatch(ids);
    }

    @Override
    public int total(ParamQuery query) {
        return paramMapper.total(query);
    }
    @Override
    public void addWithImg(Param param, MultipartFile imgFile) throws Exception {
        try {
            // 1. 上传图片到 MinIO
            String imgUrl = minioUtil.uploadFile(imgFile);
            param.setImgUrl(imgUrl);

            // 2. 设置文件名为参数值（根据需求选择）
            String originalFilename = imgFile.getOriginalFilename();
            param.setParamValue(originalFilename); // 或者保存URL

            // 3. 保存到数据库
            param.setCreateTime(new Date());
            param.setUpdateTime(new Date());
            paramMapper.insert(param);

            // 4. 同步到 MongoDB
            BlogArticle blogArticle = new BlogArticle();
            BeanUtils.copyProperties(param, blogArticle);
            mongoTemplate.save(blogArticle);

        } catch (Exception e) {
            throw new Exception("文件上传或保存失败: " + e.getMessage(), e);
        }
    }


}